package com.zl.codereview;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.zl.codereview.git.GitService;
import com.zl.codereview.review.ReviewContent;
import com.zl.codereview.util.IdeaUtils;
import com.zl.codereview.util.JOptionPaneUtils;
import com.zl.codereview.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;

import java.awt.event.MouseEvent;
import java.util.List;

public class CodeReviewShowAction extends AnAction {

    private GitService gitService = GitService.getInstance();

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        try {
            new ReviewDialog(e,1);
        } catch (Exception e1) {
            e1.printStackTrace();
            JOptionPaneUtils.warn(e1.getMessage());
        }
    }


    @Override
    public void update(@NotNull AnActionEvent e) {
        //代码评审路径
        String codeReviewPath = IdeaUtils.codeReviewPath(e);
        //当前点击所在行号
        Editor editor = e.getData(PlatformDataKeys.EDITOR);
        if (e.getProject() != null && editor != null) {
            // 获取光标所在行号
            int lineNum = editor.getCaretModel().getLogicalPosition().line + 1; // 行号从1开始计数
            List<ReviewContent> reviewContents  = IdeaUtils.parseObject(codeReviewPath);
            if(!ObjectUtils.isEmpty(reviewContents)) {
                ReviewContent reviewContent = reviewContents.stream().filter(r -> r.getNumber() == lineNum)
                        .findFirst().orElse(null);
                if (reviewContent != null) {
                    e.getPresentation().setEnabled(true);
                    return;
                }
            }
        }
        e.getPresentation().setEnabled(false);
    }


    private int getLineNum(AnActionEvent e){
        // 获取当前活动的编辑器实例
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        if (editor instanceof EditorImpl) {
            // 获取鼠标事件的点坐标
            MouseEvent mouseEvent = (MouseEvent)e.getInputEvent();
            if (mouseEvent != null) {
                // 转换为编辑器的逻辑位置
                LogicalPosition logicalPos = ((EditorImpl) editor).xyToLogicalPosition(mouseEvent.getPoint());
                // 获取点击的行号（注意：行号是从0开始计数）
                return logicalPos.line;
            }
        }
        return -1;
    }
}
